#!/bin/bash
# 用法说明
usage() {
    echo "参考答案生成助手"
    echo "用法: $0 <目标> [阶段]"
    echo "阶段参数:"
    echo "  1 或 bd : 初始构建并显示错误 (Build & Display)"
    echo "  2 或 ed : 进入编辑模式 (Edit)"
    echo "  3 或 pr : 提交并推送变更 (PR)"
    echo "示例:"
    echo "  $0 vec1 bd    # 显示vec1的初始错误"
    echo "  $0 hashmap1 3 # 提交hashmap1的答案"
}

# 参数检查
if [ $# -lt 1 ]; then
    usage
    exit 1
fi

TARGET=$1
PHASE=${2:-"bd"}  # 默认阶段为 bd

# 配置部分
EDITOR="nano"     # 可修改为 vim/emacs 等
TEST_CMD="cargo test --bin"
RUN_CMD="cargo run --bin"
FILE_DIR="exercises"

process_bd() {
    echo -e "\033[34m▶ 阶段1：原始错误捕获 - ${TARGET}\033[0m"
    
    # 强制清理环境
    cargo clean --bin ${TARGET} >/dev/null 2>&1
    
    # 测试错误
    echo -e "\n\033[33m▼ 测试命令输出 ▼\033[0m"
    echo -e "\033[33m$ cargo test --bin ${TARGET}\033[0m"
    ${TEST_CMD} ${TARGET} 2>&1 | grep -v -e 'Finished' -e 'Compiling' -e 'Downloading' -e 'Running'
    
    # 运行错误
    echo -e "\n\033[33m▼ 运行命令输出 ▼\033[0m"
    echo -e "\033[33m$ cargo run --bin ${TARGET}\033[0m"
    ${RUN_CMD} ${TARGET} 2>&1 | grep -v -e 'Finished' -e 'Compiling' -e 'Downloading'
    
    # 源码展示
    echo -e "\n\033[32m▼ 待补全源码 ▼\033[0m"
    cat ${FILE_DIR}/${TARGET}.rs
}

process_ed() {
    echo -e "\033[34m▶ 阶段2：编辑代码 - ${TARGET}\033[0m"
    
    # 打开编辑器
    ${EDITOR} ${FILE_DIR}/${TARGET}.rs

    # 源码展示
    echo -e "\n\033[32m▼ 最新源码 ▼\033[0m"
    cat ${FILE_DIR}/${TARGET}.rs

    echo -e "\n\033[33m=== 运行验证 ===\033[0m"
    ${TEST_CMD} ${TARGET} && ${RUN_CMD} ${TARGET}
}

process_pr() {
    echo -e "\033[34m▶ 阶段3：提交变更 - ${TARGET}\033[0m"
    
    # 强制清理环境  
    cargo clean

    # 添加所有相关文件
    git add ${FILE_DIR}/${TARGET}.rs
    git add makeanswer.sh  # 新增：添加脚本自身

    # 查看最新提交的文件列表
    git show --name-only

    # 检查是否有修改
    if git diff --cached --quiet; then
        echo -e "\033[33m⚠ 没有需要提交的修改\033[0m"
        return 0
    fi
    
    # 提交并推送
    git commit -m "feat: add solution for ${TARGET}"
    
    if git push; then
        echo -e "\033[32m✔ 已成功推送至远程仓库\033[0m"
        return 0
    else
        echo -e "\033[31m✘ 推送失败，请检查网络或权限\033[0m"
        return 1
    fi
}

# 主逻辑
case ${PHASE} in
    1|bd)
        process_bd
        ;;
    2|ed)
        process_ed
        ;;
    3|pr)
        process_pr
        ;;
    *)
        echo "错误：无效阶段参数"
        usage
        exit 1
        ;;
esac

exit $?
